package club.xyes.zkh.ecommerce.commons.util;

import club.xyes.zkh.ecommerce.commons.exception.InternalServerErrorException;

import java.math.BigDecimal;

/**
 * Create by 郭文梁 2019/5/6 0006 17:10
 * MoneyUtils
 * 金额相关工具类
 *
 * @author 郭文梁
 * @data 2019/5/6 0006
 */
public class MoneyUtils {
    private static final BigDecimal FEN_YUAN_RATE = BigDecimal.valueOf(100);
    private static final BigDecimal TEN = BigDecimal.TEN;

    /**
     * 将分转换成元
     *
     * @param fen 分
     * @return 元
     */
    public static String fen2Yuan(int fen) {
        return BigDecimal.valueOf(fen).setScale(2, BigDecimal.ROUND_DOWN).divide(FEN_YUAN_RATE, BigDecimal.ROUND_DOWN).toString();
    }

    /**
     * 将分转换成元
     *
     * @param fen 分
     * @return 元
     */
    public static String fen2Yuan(String fen) {
        if (TextUtil.isTrimedEmpty(fen)) {
            throw new InternalServerErrorException(
                    String.format("Could not convert fen[%s] to yuan, param is null or empty!", fen));
        }
        try {
            return fen2Yuan(Integer.parseInt(fen));
        } catch (NumberFormatException e) {
            throw new InternalServerErrorException(
                    String.format("Could not convert fen [%s] to yuan, param is not a number", fen));
        }
    }

    /**
     * 将优惠率转换为刻度字符串
     *
     * @param discountRate 优惠率
     * @return 字符串
     */
    public static String discountRateText(String discountRate) {
        BigDecimal source = new BigDecimal(discountRate);
        return source.multiply(TEN).setScale(2, BigDecimal.ROUND_DOWN).toString();
    }
}
